
#include "sys.h"
#include "dwt.h"

//使能DWT模块的功能位
#define DEMCR           ( *(unsigned int *)0xE000EDFC )
#define TRCENA          ( 0x01 << 24) // DEMCR的DWT使能位  

//0xE0001000 DWT_CTRL RW The Debug Watchpoint and Trace (DWT) unit
//使能CYCCNT计数器开始计数
#define DWT_CTRL        ( *(unsigned int *)0xE0001000 )
#define CYCCNTENA       ( 0x01 << 0 ) // DWT的SYCCNT使能位

//0xE0001004 DWT_CYCCNT RW Cycle Count register,
//CYCCNT计数器的内部值(32位无符号)


volatile unsigned int *DWT_CYCCNT  ;
volatile unsigned int *DWT_CONTROL ;
volatile unsigned int *SCB_DEMCR   ;


void reset_timer(void) {
    DWT_CYCCNT   = (unsigned int *)0xE0001004; //address of the register
    DWT_CONTROL  = (unsigned int *)0xE0001000; //address of the register
    SCB_DEMCR    = (unsigned int *)0xE000EDFC; //address of the register
    *SCB_DEMCR   = *SCB_DEMCR | 0x01000000;
    *DWT_CYCCNT  = 0; // reset the counter
    *DWT_CONTROL = 0;
}

void start_timer(void) {
    *DWT_CONTROL = *DWT_CONTROL | 1 ; // enable the counter
}

void stop_timer(void) {
    *DWT_CONTROL = *DWT_CONTROL | 0 ; // disable the counter
}

unsigned int getCycles(void) {
    return *DWT_CYCCNT;
}